package com.sgb.kjwl.viewmodel.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.provider.Contacts;
import android.text.TextUtils;

import androidx.databinding.ObservableField;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.SPUtils;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.google.gson.reflect.TypeToken;
import com.sgb.capital.utils.SPreferenceUtil;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.HomeMenuEntity;
import com.sgb.kjwl.model.entity.IndustryHomeListEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.businessmanagement.GoodsIndexMemberEntity;
import com.swgk.core.view.entity.EnterpriseEditEntity;
import com.sgb.kjwl.model.entity.request.MaterialFilterJson3;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.utils.LocationUtil;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.sgb.kjwl.view.ui.fragment.home.MaterialHomeFragment1;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.entity.MenuEntity;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author Administrator
 */
public class MaterialHomeModel1 extends BaseViewModel {

    MaterialHomeFragment1 mMaterialHomeFragment;
    public ObservableField<MaterialFilterJson3> materialFilterJson = new ObservableField<>(new MaterialFilterJson3());
    private HomeRepertory repertory;
    private Map map;
    private boolean isMenuLoaded = false;



    public MaterialHomeModel1(MaterialHomeFragment1 fragment, HomeRepertory repertory) {
        this.mMaterialHomeFragment = fragment;
        this.repertory = repertory;
    }

    public void getMenuModel(String areaCode, String id) {



        isMenuLoaded = true;
        DialogHelper.showProgressDialog(mMaterialHomeFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        if ("".equals(areaCode)) {
            areaCode = repertory.getAreaCode();
        }
        if (map == null) {
            map = new HashMap(2);
        }
        map.put("industryId", id);
        map.put("areaCode", areaCode);
        APIManager.getInstance().getMaterialAPI().getItemCatList(map).enqueue(new Callback<BaseEntity<List<MenuEntity>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<MenuEntity>>> call, @NotNull Response<BaseEntity<List<MenuEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {

                        mMaterialHomeFragment.showMenuView(response.body().getData());

                } else {
                    MToast.showToast(mMaterialHomeFragment.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<MenuEntity>>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mMaterialHomeFragment.getActivity(), t.getMessage());
            }
        });
    }

    @SuppressLint("CheckResult")
    public void getCategoryModel(String areaCode) {
        DialogHelper.showProgressDialog(mMaterialHomeFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        if ("".equals(areaCode)) {
            areaCode = repertory.getAreaCode();
        }
        repertory.getCategoryData(areaCode).subscribe(listBaseEntity -> {
            if (listBaseEntity.getData() != null && listBaseEntity.getData().size() > 0) {
                mMaterialHomeFragment.showCategoryView(listBaseEntity.getData());
            }
        }, throwable -> MLog.d(AppConstant.API_LOG, throwable.getMessage()));
    }

    public void recommendMenu() {
        NewAPIManager.getInstance().getMaterialAPI().recommendMenuNew().enqueue(new Callback<BaseEntity<List<MenuEntity>>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<List<MenuEntity>>> call, @NotNull Response<BaseEntity<List<MenuEntity>>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    SPUtils.getInstance().put(SPreferenceUtil.SAVE_GOODS_TiTLE,JSONObject.toJSONString(response.body().getData()));
                    mMaterialHomeFragment.showImageButton(response.body().getData());
                    if (response.body().getData() != null && response.body().getData().size() != 0) {
                        mMaterialHomeFragment.showImageButton(response.body().getData());
                    }
                } else {
                    MToast.showToast(mMaterialHomeFragment.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<List<MenuEntity>>> call, @NotNull Throwable t) {
                MToast.showToast(mMaterialHomeFragment.getActivity(), t.getMessage());
            }
        });
    }

    //获取跳转页需要传的数据
    public void recommendMenu(int position, boolean isMap) {
        APIManager.getInstance().getMaterialAPI().recommendMenuNew().enqueue(new ICallBack<BaseEntity<List<MenuEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MenuEntity>> data) {
                mMaterialHomeFragment.showImageButtonData(data.getData(), position, isMap);
            }
        });
    }

    public void recomandCate(boolean isRefresh) {
        Type type = new TypeToken<List<HomeMenuEntity>>() {
        }.getType();
        Object obj = DatalUtils.getInstance().getData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU, type);
        List<HomeMenuEntity> data = new ArrayList<>();
        if (null != obj && isRefresh == false) {
            List<HomeMenuEntity> dataList = (List<HomeMenuEntity>) obj;
            data.addAll(dataList);
            mMaterialHomeFragment.showRecommendCate(data, isRefresh);
        }
        if (data.size() == 0 || isRefresh) {
            getTuijianData(isRefresh);
        }
    }

    public void getIndustryList() {
        DialogHelper.showProgressDialog(mMaterialHomeFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsAPI().getIndustryList().enqueue(new Callback<BaseEntity<IndustryHomeListEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<IndustryHomeListEntity>> call, @NotNull Response<BaseEntity<IndustryHomeListEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    List<MenuEntity> datas = new ArrayList<>();
                    if(response.body().getData().getIndustryInfo().size()>0){
                        for (IndustryHomeListEntity.IndustryItem industryItem : response.body().getData().getIndustryInfo()) {
                            MenuEntity data = new MenuEntity();
                            data.setAppIcon(industryItem.getIcon());
                            data.setId(industryItem.getId()+"");
                            data.setName(industryItem.getName());
                            data.setUrl(industryItem.getIcon());
                            datas.add(data);
                        }
                    }
                    mMaterialHomeFragment.showIndustry(datas);
                } else {
                    MToast.showToast(mMaterialHomeFragment.getActivity(), response.message());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<IndustryHomeListEntity>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
                MToast.showToast(mMaterialHomeFragment.getActivity(), t.getMessage());
            }
        });
    }

    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        DialogHelper.showProgressDialog(mMaterialHomeFragment.getActivity(), null, "登录中", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<LoginEntity>> call, @NotNull Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(mMaterialHomeFragment.getActivity(), SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        mMaterialHomeFragment.requireActivity().startActivity(intent);
                    } else {
                        //登录成功逻辑
                        saveUserInfo(response.body().getData());
                        mMaterialHomeFragment.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(mMaterialHomeFragment.requireActivity(), 1, response.body().getData().getPhone());
                        getUserInfo();
                    }
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<LoginEntity>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog(mMaterialHomeFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(@NotNull Call<BaseEntity<UserMsgEntity>> call, @NotNull Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getData() == null) {
                    return;
                }
                if ("ok".equals(response.body().getState())) {
                    mMaterialHomeFragment.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(mMaterialHomeFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(@NotNull Call<BaseEntity<UserMsgEntity>> call, @NotNull Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());
    }

    public void saveProvinceModel(String name, String code) {
        repertory.setAreaCode(code);
        repertory.setAreaName(name);
    }

    /**
     * 我的成员
     */
    public void getMember() {
        DialogHelper.showProgressDialog(mMaterialHomeFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getMemberIndex("1").enqueue(new Callback<BaseEntity<GoodsIndexMemberEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<GoodsIndexMemberEntity>> call, Response<BaseEntity<GoodsIndexMemberEntity>> response) {
                if (response.body() != null && "ok".equals(response.body().getState())) {
                    mMaterialHomeFragment.requestMemberResult(response.body().getData());
                } else {
                    mMaterialHomeFragment.requestMemberResult(null);
                }
                DialogHelper.dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseEntity<GoodsIndexMemberEntity>> call, Throwable t) {
                mMaterialHomeFragment.requestMemberResult(null);
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 我的会员
     */
    public void getLeague() {
        DialogHelper.showProgressDialog(mMaterialHomeFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getMemberIndex("2").enqueue(new Callback<BaseEntity<GoodsIndexMemberEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<GoodsIndexMemberEntity>> call, Response<BaseEntity<GoodsIndexMemberEntity>> response) {
                if (response.body() != null && "ok".equals(response.body().getState())) {
                    mMaterialHomeFragment.requestLeagueResult(response.body().getData());
                } else {
                    mMaterialHomeFragment.requestLeagueResult(null);
                }
                DialogHelper.dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseEntity<GoodsIndexMemberEntity>> call, Throwable t) {
                mMaterialHomeFragment.requestLeagueResult(null);
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    /**
     * 我的关注
     */
    public void getCompanyFocus() {
        Map<String, Object> map = new HashMap<>();
        map.put("userNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, ""));
        map.put("page", 1);
        map.put("limit", 6);
        DialogHelper.showProgressDialog(mMaterialHomeFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getCompanyFocus(map).enqueue(new Callback<BaseEntity<ProListEntity<List<GoodsIndexMemberEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<GoodsIndexMemberEntity>>>> call, Response<BaseEntity<ProListEntity<List<GoodsIndexMemberEntity>>>> response) {
                if (response.body() != null && response.body().getState() != null && APIManager.RESPONSE_OK.equals(response.body().getState())) {
                    mMaterialHomeFragment.requestCompanyFocus(response.body().getData().getList());
                } else {
                    mMaterialHomeFragment.requestCompanyFocus(null);
                }
                DialogHelper.dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<GoodsIndexMemberEntity>>>> call, Throwable t) {
                mMaterialHomeFragment.requestCompanyFocus(null);
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    /**
     * 我的推荐
     */
    public void getSupplierListModel() {
        Map<String, Object> map = new HashMap<>();
        map.put("province", repertory.getAreaCode());
        map.put("page", 1);
        map.put("limit", 6);
        if (LocationUtil.isOpenLocation(mMaterialHomeFragment.getActivity()) && LocationUtil.currentLocationIsValid()) {
            map.put("longitude", String.valueOf(LocationUtil.getCurrentLongitude()));
            map.put("latitude", String.valueOf(LocationUtil.getCurrentLatitude()));
        } else {
            map.put("longitude", "0");
            map.put("latitude", "0");
        }
        DialogHelper.showProgressDialog(mMaterialHomeFragment.getActivity(), null, "加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getGoodsReleasedAPI().getIndexSupplierRecommendation(map).enqueue(new Callback<BaseEntity<ProListEntity<List<GoodsIndexMemberEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ProListEntity<List<GoodsIndexMemberEntity>>>> call, Response<BaseEntity<ProListEntity<List<GoodsIndexMemberEntity>>>> response) {
                if (response.body() != null && response.body().getState() != null && APIManager.RESPONSE_OK.equals(response.body().getState())) {
                    mMaterialHomeFragment.requestSupplierResult(response.body().getData().getList());
                } else {
                    mMaterialHomeFragment.requestSupplierResult(null);
                }
                DialogHelper.dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseEntity<ProListEntity<List<GoodsIndexMemberEntity>>>> call, Throwable t) {
                mMaterialHomeFragment.requestSupplierResult(null);
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    int i = 0;

    /**
     * 根据用户身份信息获取展示的企业标题
     */
    public void getCompanyTitleList(String areaCode) {
        i++;
        areaCode = repertory.getAreaCode();
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.AREA_CODE, repertory.getAreaCode());
        int code = TextUtils.isEmpty(areaCode) ? 615000 : Integer.valueOf(areaCode);
        APIManager.getInstance().getBigHomeAPI().getEnterpriseRecListNew(code).enqueue(new ICallBack<BaseEntity<List<EnterpriseEditEntity>>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<List<EnterpriseEditEntity>> data) {
                i = 0;
                mMaterialHomeFragment.initCompanyTitle(data.getData());
            }

            @Override
            public void onFailureWithEntity(BaseEntity entity) {
                super.onFailureSwitchErrCode(entity);
                if (entity != null && i<2){
                    if ("53999".equals(entity.getErrCode())) {
                        getCompanyTitleList("");
                    }
                }
            }
        });
    }


    public void firstRecommendMenu() {
        APIManager.getInstance().getMaterialAPI().recommendMenuNew().enqueue(new ICallBack<BaseEntity<List<MenuEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<MenuEntity>> data) {
                mMaterialHomeFragment.setRecommendMenuData(data.getData());
            }
        });
    }

    /**
     * 获取大首页推荐数据
     *
     * @param isRefresh
     */
    private void getTuijianData(boolean isRefresh) {
        APIManager.getInstance().getBigHomeAPI().getAllRecomandCate().enqueue(new ICallBack<BaseEntity<List<HomeMenuEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<HomeMenuEntity>> data) {
                if (data == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    //获取从网络请求下来的数据的哈希值
                    String mHashNet = DatalUtils.getInstance().strToHashKey(data.getData());
                    if (data.getData() != null && data.getData().size() > 0) {
                        String cacheOperationHash = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU);
                        if (!mHashNet.equals(cacheOperationHash)) {
                            mMaterialHomeFragment.showRecommendCate(data.getData(), false);
                            DatalUtils.getInstance().putData(MkvUtils.CacheModular, CacheMarker.HOME_MEAU, data.getData());
                        } else {
                            mMaterialHomeFragment.showRecommendCate(data.getData(), isRefresh);
                        }
                    }
                } else {
                    MToast.showToast(mMaterialHomeFragment.getActivity(), data.getMsg());
                }
            }
        });
    }


    public void getIndustryListdata(String areaCode, String id){

        NewAPIManager.getInstance().getGoodsAPI().getIndustryList().enqueue(new Callback<BaseEntity<IndustryHomeListEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<IndustryHomeListEntity>> call, Response<BaseEntity<IndustryHomeListEntity>> response) {
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if(response.body().getData().getIsEnabled()==1&&response.body().getData().getIndustryInfo().size()>0){
                        mMaterialHomeFragment.ShowMenuViewTabIndustry(response.body().getData().getIndustryInfo());

                    }else{
                        getMenuModel(areaCode,id);
                    }
                } else {
                    MToast.showToast(mMaterialHomeFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<IndustryHomeListEntity>> call, Throwable t) {
                MToast.showToast(mMaterialHomeFragment.getActivity(), t.getMessage());
            }
        });

    }


    public void getIndustryId(String firstCategoryId, String secondCategoryId, String thirdCategoryId, int position){
        NewAPIManager.getInstance().getGoodsAPI().getIndustryid(firstCategoryId).enqueue(new Callback<BaseEntity<Object>>() {
            @Override
            public void onResponse(Call<BaseEntity<Object>> call, Response<BaseEntity<Object>> response) {
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if(response.body().getData()!=null) {
                        JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(response.body().getData()));
                        if (json.get("id") != null) {
                            mMaterialHomeFragment.startForResemble(firstCategoryId, secondCategoryId, thirdCategoryId, position, json.getLong("id") + "");
                        } else {
                            mMaterialHomeFragment.startForResemble(firstCategoryId, secondCategoryId, thirdCategoryId, position, "-1");
                        }
                    }else{
                        mMaterialHomeFragment.startForResemble(firstCategoryId, secondCategoryId, thirdCategoryId, position, "-1");
                    }

                } else {
                    MToast.showToast(mMaterialHomeFragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<Object>> call, Throwable t) {
                MToast.showToast(mMaterialHomeFragment.getActivity(), t.getMessage());
            }
        });
    }
}
